<?php

namespace plugin\laoha\app\controller;

use plugin\laoha\app\model\Cate;
use plugin\laoha\app\model\Post;
use plugin\laoha\app\model\Act;
use plugin\laoha\app\model\Nav;
use plugin\laoha\app\model\Comment;
use plugin\laoha\app\common\NavClass;
use plugin\laoha\app\common\CateClass;
use Intervention\Image\ImageManagerStatic as Image;
use plugin\admin\app\model\User;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class PostController extends Crud
{
    protected $noNeedLogin = ['index', 'list', 'select', 'show', 'search', 'detail','user'];

    public function __construct()
    {
        $this->model = new Post;
        $this->rules = $this->getRules();
    }

    public function index(Request $request): Response
    {

        $title = '文章列表';
        $init = [
            'cur_admin_id'=> admin_id(),
            'group' => $request->input('group', ''),
            'active' => '/app/laoha/post',
            'title' => $title,
            'bread' => $title . '|/app/laoha/post',
            'rules' => $this->rules,
            'data' => $this->list($request),
            'config' => config('plugin.laoha.set.app.post', [])
        ];
        return $this->out($init, 'post/index');
    }

    public function detail(Request $request)
    {
        $config = config('plugin.laoha.set.app.post', []);
        $id = $request->input('id');      
        if(empty($id)){
            if (request()->api) {
                return json_fail('未指定ID');
            } else {
                return '未指定ID';
            }            
        }
        if(!empty($request->input('_next'))){  //下一篇
            $post = $this->model->whereHas('cate', function ($query) {
                $query->where('status', 0)->where('is_hidden',0);
            })->with(['cate:id,title,status'])->where('status',0)->where('id','<',$id)->orderBy('id','desc')->first();
        }elseif(!empty($request->input('_pre'))){  //上一篇
            $post = $this->model->whereHas('cate', function ($query) {
                $query->where('status', 0)->where('is_hidden',0);
            })->with(['cate:id,title,status'])->where('status',0)->where('id','>',$id)->first();
        }else{  //本篇，状态不限止，后台管理员和本人可查看
            $post = $this->model->with(['cate:id,title,status'])->find($id);
        }
        //return json($post);
        if ($post) {
            //非后台管理员或本人不能查看未审核内容
            if (!(admin_id() || $this->canAccess('owner',$post->user_id)) && (!empty($post->status) || !empty($post->cate->status))) {
                if (request()->api) {
                    return json_fail('记录禁止显示');
                } else {
                    return '记录禁止显示';
                }
            }
            //阅读计数加一
            $this->add($request, ['id' => $post->id, 'field' => 'views']);
            $post->views++;
            //是否已收藏
            if (user_id() && isset($config['acts']['collect'])) {
                if (Act::where(['root_id' => $post->id, 'root' => 'post', 'user_id' => user_id(), 'act' => 'collect'])->first()) {
                    $post->collect = 1;
                } else {
                    $post->collect = 0;
                }
            }
        } else {
            if (request()->api) {
                return json_fail('记录不存在');
            } else {
                return '记录不存在';
            }
        }

        $init = [
            'title' => $post->title,
            'bread' => ['文章|/app/laoha/post', $post->title],
            'rules' => $this->rules,
            'data' => $post,
            'config' => $config
        ];
        return $this->out($init, 'post/detail');
    }

    /**
     * 列表
     * @param $request
     */
    public function list(Request $request)
    {
        $this->set = [
            'with' => '',
            'page_type' => 1,
            'hidden' => 'content',
            'like_where' => 'title,content,pos',
            'status'=>0     //列表中只允许已审核内容
        ];
        if (empty($request->input('cate_id'))) {   
            $this->builder = $this->model->whereHas('cate', function ($query) {
                $query->where('status', 0)->where('is_hidden', 0);
            })->with(['cate:id,title,status,is_hidden']);
        } else {                 //指定分类ID,可以是多个,这里打开隐藏分类，可查看隐藏分类内容
            $this->builder = $this->model->whereHas('cate', function ($query) {
                $query->where('status', 0);
            })->with(['cate:id,title,is_hidden']);
        }
        //评论数
        if (config('plugin.laoha.set.app.post.comment', false)) {
            $this->builder = $this->builder->withCount('comments');
        }
        return parent::list($request);
    }
    
    public function search(Request $request)
    {
        $k = trim($request->input('_k', ''));
        if (empty($k)) {
            if (request()->api) {
                return json_fail('请输入搜索关键词');
            } else {
                return '请输入搜索关键词';
            }
        }
        $this->set = [
            'with' => '',
            'page_type' => 1,
            'hidden' => '',
            'select' => 'id,title,cate_id,content',
            'status'=>0     //列表中只允许已审核内容
        ];
        $config = config('plugin.laoha.set.app.post', []);
        
        $this->builder = $this->model->whereHas('cate', function ($query) {
            $query->where('status', 0)->where('is_hidden', 0);  //隐藏类不包括在搜索中
        });
        $this->builder = $this->builder->where(function ($query) use ($k) {
            $query->where('title', 'like', '%' . $k . '%')->orWhere('content', 'like', '%' . $k . '%');
        });
        $data = parent::list($request);
        if (!empty($data['items'])) {
            foreach ($data['items'] as $i => $d) {
                $d['title'] = strip_tags($d['title']);
                $d['title'] = str_replace($k, "<span class='text-danger'>$k</span>", $d['title']);
                $d['content'] = mb_substr(strip_tags($d['content']), 0, 250, 'utf-8');
                $d['content'] = str_replace($k, "<span class='text-danger'>$k</span>", $d['content']);
                $data['items'][$i] = $d;
            }
        }
        $init = [
            'k' => $k,
            'active' => '/app/laoha/post',
            'title' => '搜索',
            'bread' => ['文章|/app/laoha/post', '搜索关键词"' . $k . '"'],
            'rules' => $this->rules,
            'data' => $data,
            'config' => $config
        ];
        return $this->out($init, 'post/search');
    }


}
